package com.cugmarket.controller.product.user;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.cugmarket.constant.MessageConstant;
import com.cugmarket.dto.Result;
import com.cugmarket.dto.UserDTO;
import com.cugmarket.entity.ProductInfo;
import com.cugmarket.entity.ProductType;
import com.cugmarket.mapper.ProductInfoMapper;
import com.cugmarket.mapper.ProductTypeMapper;
import com.cugmarket.service.ProductCollectService;
import com.cugmarket.service.ProductInfoService;
import com.cugmarket.service.ProductTypeService;
import com.cugmarket.service.UserService;
import com.cugmarket.utils.UserHolder;
import com.cugmarket.vo.PageVO;
import com.cugmarket.vo.ProductInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import java.io.IOException;
import java.util.List;

import static com.cugmarket.constant.MessageConstant.*;

@Slf4j
@RestController
@RequestMapping("/user/productInfo")
public class ProductInfoController {
    @Resource
    private ProductInfoService productInfoService;
    @Resource
    private ProductCollectService productCollectService;

    @Resource
    private ProductTypeMapper productTypeMapper;

    @Resource
    private  UserService userService;


    /**
     * 根据地区编码进行商品查询
     * @param currentPage
     * @param pageSize
     * @param adCode
     * @return
     */
    @GetMapping("/position")
    public Result getByPosition(@RequestParam("currentPage") Integer currentPage,
                                @RequestParam("pageSize") Integer pageSize,
                                @RequestParam(value = "adCode") String adCode) {
        String adCodeToUse = (adCode != null && adCode.length() > 4) ? adCode.substring(0, 4) : adCode;
        PageVO pageVO;
        pageVO = productInfoService.selectListByAdCode(currentPage, pageSize, adCodeToUse);
        if (pageVO != null && !pageVO.getRecords().isEmpty()) {
            return Result.success(pageVO);
        }
        // 没查到数据
        return Result.error(IS_EMPTY);
    }

    /**
     * 根据id查询商品信息
     * @param id
     * @return
     */
    @GetMapping("/id")
    public Result<ProductInfo> getById(@RequestParam("id") String id) {
        ProductInfoVO productInfoVO = productInfoService.getByProductId(id);
        return Result.success(productInfoVO);
    }

    /**
     * 查询所有或按类型查询
     * @return
     */
    @GetMapping("/list")
    public Result list(@RequestParam("currentPage") Integer currentPage,
                       @RequestParam("pageSize") Integer pageSize,
                       @RequestParam(value = "typeId", required = false) String typeId) {
        PageVO pageVO;

        // 判断是否传递了 typeId，按条件查询
        if (typeId != null && !typeId.isEmpty()) {
             pageVO = productInfoService.selectListByType(currentPage, pageSize, typeId);
        } else {
             pageVO = productInfoService.selectList(currentPage, pageSize);
        }
        if (pageVO != null && !pageVO.getRecords().isEmpty()) {
            return Result.success(pageVO);
        }
        // 没查到数据
        return Result.error(IS_EMPTY);
    }


    /**
     * 新增商品信息
     * @param productInfo
     * @return
     */
    @PostMapping("/add")
    public Result add(@RequestBody ProductInfo productInfo) {
        String userId = UserHolder.getUser();
        productInfo.setUserId(userId);
        if (!productInfoService.save(productInfo)) {
            return Result.error(INSERT_ERROR);
        }
        return Result.success(UPDATE_SUCCESS);
    }

    /**
     * 删除商品信息
     * @param id
     * @return
     */
    @DeleteMapping("/delete")
    public Result del(@RequestParam("id") String id) {
        if (id == null) {
            return Result.error(DELETE_ERROR);
        }
        if (!productInfoService.removeById(id)) {
            return Result.error(DELETE_ERROR);
        }
        return Result.success(UPDATE_SUCCESS);
    }

    /**
     * 更新商品信息
     * @param productInfo
     * @return
     */
    @PutMapping("/update")
    public Result update(@RequestBody ProductInfo productInfo) {
        String userId = UserHolder.getUser();
        productInfo.setUserId(userId);
        boolean flag = productInfoService.updateById(productInfo);
        if (!flag) {
            return Result.error(UPDATE_ERROR);
        }
        return Result.success(UPDATE_SUCCESS);
    }

    /**
     * 获取商品分类
     * @return
     */
    @GetMapping("/types")
    public Result getAllTypes() {
        LambdaQueryWrapper<ProductType> queryWrapper = new LambdaQueryWrapper<ProductType>()
                .orderByDesc(ProductType::getId);
        List<ProductType> productTypes = productTypeMapper.selectList(queryWrapper);
        if (productTypes.isEmpty()) {
            return Result.error(SEARCH_ERROR);
        }
        return Result.success(productTypes);
    }

    /**
     * 根据userId获取已发布商品列表 status=3,6,9
     * @param currentPage
     * @param pageSize
     * @return
     */
    @GetMapping("/published")
    public Result getPublishProductList(@RequestParam("currentPage") Integer currentPage,
                                     @RequestParam("pageSize") Integer pageSize) {
        String userId = UserHolder.getUser();
        PageVO pageVO = productInfoService.selectListByUserIdPublish(currentPage, pageSize, userId);
        if (pageVO != null && !pageVO.getRecords().isEmpty()) {
            return Result.success(pageVO);
        }
        return Result.error(IS_EMPTY);
    }

    /**
     * 根据userId获取已卖出商品列表 status=12
     * @param currentPage
     * @param pageSize
     * @return
     */
    @GetMapping("/sold")
    public Result getSoldProductList(@RequestParam("currentPage") Integer currentPage,
                                   @RequestParam("pageSize") Integer pageSize) {
        String userId = UserHolder.getUser();
        PageVO pageVO = productInfoService.selectListByUserIdSold(currentPage, pageSize, userId);
        if (pageVO != null && !pageVO.getRecords().isEmpty()) {
            return Result.success(pageVO);
        }
        return Result.error(IS_EMPTY);
    }

    /**
     * 根据userId获取已购买商品列表
     * @param currentPage
     * @param pageSize
     * @return
     */
    @GetMapping("/purchased")
    public Result getPurchasedProductList(@RequestParam("currentPage") Integer currentPage,
                                     @RequestParam("pageSize") Integer pageSize) {
        String userId = UserHolder.getUser();
        PageVO pageVO = productInfoService.selectListByUserIdSold(currentPage, pageSize, userId);
        if (pageVO != null && !pageVO.getRecords().isEmpty()) {
            return Result.success(pageVO);
        }
        return Result.error(IS_EMPTY);
    }

    /**
     * 根据userId获取已收藏商品列表
     * @param currentPage
     * @param pageSize
     * @return
     */
    @GetMapping("/collected")
    public Result getCollectedProductList(@RequestParam("currentPage") Integer currentPage,
                                          @RequestParam("pageSize") Integer pageSize) {
        String userId = UserHolder.getUser();
        PageVO pageVO = productInfoService.selectListByUserIdCollect(currentPage, pageSize, userId);
        if (pageVO != null && !pageVO.getRecords().isEmpty()) {
            return Result.success(pageVO);
        }
        return Result.error(IS_EMPTY);
    }

    /**
     * 根据关键词分词搜索商品
     * @param currentPage 当前页
     * @param pageSize 每页显示的记录数
     * @param condition 关键词
     * @return 商品列表
     * @throws IOException
     */
    @GetMapping("/essearch")
    public Result getProductByCondition(@RequestParam("currentPage") Integer currentPage,
                                        @RequestParam("pageSize") Integer pageSize,
                                @RequestParam("condition") String condition) throws IOException {
        PageVO pageVO = productInfoService.getProductByCondition(currentPage, pageSize, condition);
        if (pageVO != null && !pageVO.getRecords().isEmpty()) {
            return Result.success(pageVO);
        }
        return Result.error(IS_EMPTY);
    }
}
